<template>
  <div ref="el" class="chart"></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { onMounted, onBeforeUnmount, ref, watch, computed, type PropType } from 'vue';

echarts.use([LineChart, TitleComponent, TooltipComponent, GridComponent, CanvasRenderer]);

const props = defineProps({
  timeline: { type: Array as PropType<Array<{ month: string; count: number }>>, required: true },
  title: { type: String, default: '按月文章数量' }
});

const el = ref<HTMLDivElement | null>(null);
let chart: echarts.ECharts | null = null;

const x = computed(() => props.timeline.map(i => i.month));
const y = computed(() => props.timeline.map(i => i.count));

function render() {
  if (!el.value) return;
  if (!chart) chart = echarts.init(el.value, undefined, { renderer: 'canvas' });
  chart.setOption({
    backgroundColor: 'transparent',
    title: { 
      text: props.title, 
      textStyle: { 
        color: '#f8fafc', 
        fontSize: 16,
        fontWeight: 'bold'
      } 
    },
    tooltip: { 
      trigger: 'axis',
      backgroundColor: 'rgba(15, 23, 42, 0.9)',
      borderColor: 'rgba(37, 99, 235, 0.3)',
      textStyle: {
        color: '#f8fafc'
      }
    },
    grid: { left: 40, right: 16, top: 40, bottom: 30 },
    xAxis: { 
      type: 'category', 
      data: x.value, 
      axisLine: { lineStyle: { color: 'rgba(248, 250, 252, 0.3)' } }, 
      axisLabel: { color: '#f8fafc', fontSize: 11 },
      axisTick: { lineStyle: { color: 'rgba(248, 250, 252, 0.3)' } }
    },
    yAxis: { 
      type: 'value', 
      minInterval: 1, 
      axisLine: { lineStyle: { color: 'rgba(248, 250, 252, 0.3)' } }, 
      splitLine: { lineStyle: { color: 'rgba(248, 250, 252, 0.1)' } }, 
      axisLabel: { color: '#f8fafc', fontSize: 11 },
      axisTick: { lineStyle: { color: 'rgba(248, 250, 252, 0.3)' } }
    },
    series: [
      { type: 'line', data: y.value, smooth: true, symbol: 'circle', symbolSize: 8, lineStyle: { color: '#2563eb' }, itemStyle: { color: '#2563eb' }, areaStyle: { color: 'rgba(37, 99, 235, 0.12)' } }
    ]
  });
}

const onResize = () => chart?.resize();
onMounted(() => { render(); window.addEventListener('resize', onResize); });
onBeforeUnmount(() => { window.removeEventListener('resize', onResize); chart?.dispose(); chart = null; });
watch([x, y], render);
</script>

<style scoped>
.chart { width: 100%; height: 260px; }
</style>

